function output = CalculateMarkerTimings()
%CALCULATEMARKERTIMINGS()
% Uses the markerinformation (events) in the datasets to extract timing
% information about the experiment

diary('MarkerTimings.txt');
disp('Deleting previous MarkerTimings.txt');
diary off;
delete('MarkerTimings.txt');


Subjects;
fnS = fieldnames(subject);
for s = 1:length(fnS)
    subjectinfo = subject.(fnS{s});
    diary('MarkerTimings.txt');
    disp('=================================================')
    disp(subjectinfo.Name);
    diary off;
    for d = 1:length(subjectinfo.Datasets)
        dataset = subjectinfo.Datasets(d).PreprocessedFilename;
        timing = GetTimings( ...
            subjectinfo.Datasets(d).PreprocessedFilename, ...
            subjectinfo.Datasets(d).Type);
        diary('MarkerTimings.txt');
        disp('-------------------------------------------------')
        % Find the date of the original data
        dt = subjectinfo.OriginalData(find([subjectinfo.OriginalData.DestinationDataset] == d)).DateRecorded;
        disp(['   Dataset: ' dataset ' (' subjectinfo.Datasets(d).Type ', ' datestr(dt) ')']);
        for i = 1:length(timing)
            seqs = timing(i).Sequences;
            if isempty(seqs)
                disp(['     Timing of ' timing(i).Start '-->' timing(i).End ':  0 valid.']);
            else
                disp(['     Timing of ' timing(i).Start '-->' timing(i).End ':  ' num2str(size(seqs,1)) ' valid, avg of ' num2str(mean(seqs(:,2) - seqs(:,1))) 's, std of ' num2str(std(seqs(:,2) - seqs(:,1))) 's.']);
%                 disp('     Stimulus     Response         Diff'); disp([seqs (seqs(:,2)-seqs(:,1))]);
                disp('     Diff (s)'); disp(seqs(:,2)-seqs(:,1));
            end
        end
        diary off;
    end
end

end


function timingSequences = GetTimings(dataset, experimentType)

EEG = pop_loadset('filename', dataset);
EEG = eeg_checkset( EEG );
types = {EEG.event.type}';
latencies = [EEG.event.latency]'/EEG.srate;

switch experimentType
    case 'FaceHouse'
        timingSequences(1) = FindMarkerSequences('S-FH-FI', 'S-Rest-10', 'S-FH-F', 'R-FH-F', types, latencies);
        timingSequences(2) = FindMarkerSequences('S-FH-FI', 'S-Rest-10', 'S-FH-H', 'R-FH-H', types, latencies);
    case 'Sphere'
        timingSequences(1) = FindMarkerSequences('S-SC-U', 'S-Rest-10', 'S-SC-L', 'R-SC-L', types, latencies);
        timingSequences(2) = FindMarkerSequences('S-SC-U', 'S-Rest-10', 'S-SC-R', 'R-SC-R', types, latencies);
    case 'SphereVoluntary'
        timingSequences(1) = FindMarkerSequences('S-SV-LI', 'S-Rest-10', 'S-SV-L', 'R-SV-LW', types, latencies);
        timingSequences(2) = FindMarkerSequences('S-SV-LI', 'S-Rest-10', 'S-SV-R', 'R-SV-RW', types, latencies);
    case 'Sphere Intermittend'
        timingSequences(1) = FindMarkerSequences('S-Rest-10', 'S-Rest-10', 'S-SI-On', 'R-SI-R', types, latencies);
        timingSequences(2) = FindMarkerSequences('S-Rest-10', 'S-Rest-10', 'S-SI-On', 'R-SI-L', types, latencies);
    otherwise
        error(['Unknown experiment type: ' experimentType]);
end

end


function timingSequences = FindMarkerSequences(preMarker, postMarker, timingStartMarker, timingEndMarker, types, latencies)

validArea = false(size(types));
pre = find(strcmp(types, preMarker));
post = find(strcmp(types, postMarker));
for i = 1:length(pre)
    firstPostAfterPre = post(find(post>pre(i),1,'first'));
    if ~isempty(firstPostAfterPre)
        validArea(pre(i)+1:firstPostAfterPre-1) = true;
    end
end

seqs = [];
starts = find(strcmp(types, timingStartMarker) & validArea);
ends = find(strcmp(types, timingEndMarker) & validArea);
for i = 1:length(starts)
    firstEndAfterStart = ends(find(ends>starts(i),1,'first'));
    if ~isempty(firstEndAfterStart) ...
            && latencies(firstEndAfterStart) - latencies(starts(i)) < 3 % test for max 2 seconds between markers..
        seqs = [seqs; latencies(starts(i)), latencies(firstEndAfterStart)];
    end
end

timingSequences.Start = timingStartMarker;
timingSequences.End = timingEndMarker;
timingSequences.Sequences = seqs;
end